package com.resou.reader.search;

import android.arch.lifecycle.LifecycleOwner;
import android.content.ContentValues;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.resou.reader.api.ApiImp;
import com.resou.reader.api.entry.CommonData;
import com.resou.reader.api.entry.SearchBean;
import com.resou.reader.bookshelf.readhistory.datasupport.SearchHistory;
import com.resou.reader.api.service.SearchService;
import com.resou.reader.base.m.IModel;
import com.resou.reader.base.p.BasePresenter;
import com.resou.reader.utils.log.RsLog;
import com.resou.reader.mine.IView.UserInstance;

import org.litepal.LitePal;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by ${Garrett} on 2018/9/6.
 * Contact me krouky@outlook.com
 */
public class SearchPresenter extends BasePresenter<ISearchView, IModel> {
    public static int HOT_SIZE_MAX = 8;//最多展示的hot数

    private SearchService mService;

    public SearchPresenter(ISearchView view) {
        this.view = view;
        mService = ApiImp.getInstance().getService(SearchService.class);
    }

    @Override
    public void onCreate(@NonNull LifecycleOwner owner) {
        super.onCreate(owner);
        getHotPush();//大家都在搜
        getAllHistory();//搜索历史
    }

    private boolean isRequestInProgress = false;

    private int mCurrentPage = 0;

    private static final String TAG = "Search2Presenter-App";

    public void search(final String text) {
        if (TextUtils.isEmpty(text)) {
            Toast.makeText(view.getViewContext(), "请输入搜索内容", Toast.LENGTH_SHORT).show();
            return;
        }
        //存记录
        saveHistory(text);
        if (isRequestInProgress) {
            return;
        }
        isRequestInProgress = true;
        mService.search(text, UserInstance.getToken(), 0, 10)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .as(this.bindLifecycle())
                .subscribe(commonDataResult -> {
                            CommonData<List<SearchBean>> commonData = commonDataResult.getData();
                            if (commonData != null) {
                                view.showSearchResult(commonData.getData(), text);
                            }
                            mCurrentPage =  1;
                            isRequestInProgress = false;
                        }, Throwable -> {
                            isRequestInProgress = false;
                        }
                );
    }

    public void searchNext(final String text) {
        if (TextUtils.isEmpty(text)) {
            Toast.makeText(view.getViewContext(), "请输入搜索内容", Toast.LENGTH_SHORT).show();
            return;
        }
        if (isRequestInProgress) {
            return;
        }
        isRequestInProgress = true;
        mService.search(text, UserInstance.getToken(), mCurrentPage, 10)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .as(this.bindLifecycle())
                .subscribe(commonDataResult -> {
                            CommonData<List<SearchBean>> commonData = commonDataResult.getData();
                            if (commonData != null) {
                                view.addSearchResult(commonData.getData(), text);
                            }
                            mCurrentPage = mCurrentPage + 1;
                            isRequestInProgress = false;
                        }, Throwable -> {
                            isRequestInProgress = false;
                        }
                );
    }

    public void getHotPush() {
        mService.searchPush()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .as(this.bindLifecycle())
                .subscribe(commonDataResult -> {
                    if (commonDataResult.getData() != null) {
                        view.showHot(commonDataResult.getData().getData());
                    }
                }, Throwable::printStackTrace);
    }

    /**
     * 获取搜索数据
     */
    public void getAllHistory() {
        Observable.create((ObservableOnSubscribe<List<SearchHistory>>) emitter -> {
            List<SearchHistory> list = LitePal.select("history").order("updateTime desc").find(SearchHistory.class);
            emitter.onNext(list);
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .as(this.bindLifecycle())
                .subscribe(searchHistories -> {
                    view.showHistory(searchHistories);
                }, throwable -> {

                });
    }

    /**
     * 存搜索数据
     */
    private void saveHistory(final String historyStr) {
        Observable.create((ObservableOnSubscribe<Integer>) emitter -> {
            List<SearchHistory> list = LitePal.where("history = ?", historyStr).find(SearchHistory.class);
            int id = -1;
            if (list != null && list.size() > 0) {
                id = list.get(0).getId();
                RsLog.d("searchHistory 11 id:" + id);
            } else {
                RsLog.d("list == null || size == 0");
            }
            emitter.onNext(id);
        }).observeOn(Schedulers.io()).observeOn(Schedulers.io()).as(this.<Integer>bindLifecycle())
                .subscribe(integer -> {
                    int id = integer;
                    if (id != -1) {
                        ContentValues values = new ContentValues();
                        values.put("updateTime", System.currentTimeMillis());
                        LitePal.update(SearchHistory.class, values, id);
                    } else {
                        SearchHistory temp = new SearchHistory(historyStr, System.currentTimeMillis());
                        temp.save();
                    }
                });
    }


    /**
     * 删除所有搜索历史
     */
    public void deleteAllHistory() {
        Observable.create((ObservableOnSubscribe<Boolean>) emitter -> {
            LitePal.deleteAll(SearchHistory.class);
            emitter.onNext(true);
        }).subscribeOn(Schedulers.io()).observeOn(Schedulers.io())
                .subscribe();
    }
}
